package com.kevin.d.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kevin.d.R;
import com.kevin.d.inf.LinkCallback;

import java.util.ArrayList;
import java.util.List;

public class LinkListTwoFragment<T> extends Fragment implements View.OnClickListener, TextWatcher, LinkListManager.MListener<T> {

    public final static String EXTRA_DATA = "data";//数据，jsonArray格式 字符串
    public final static String EXTRA_FIRST_LEVEL_NAME = "firstLevelName";//第一层级名称


    private EditText etKeyword;


    private Activity mActivity;
    private LinkCallback<T> callback;
    private String firstLevelName;


    private LinkListManager<T> llManagerLeft;
    private LinkListManager<T> llManagerRight;
    private RecyclerView rvLeft;
    private RecyclerView rvRight;
    private final String tagLeft = "left";
    private final String tagRight = "right";

    private List<List<T>[]> historyData = new ArrayList<>();//记录每一层级的数据,返回时使用
    private List<String> title = new ArrayList<>();

    private LinearLayout llTitle;
    private HorizontalScrollView mScrollview;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_link_list_1, null);
        initView(view);
        initData();
        return view;
    }


    public static LinkListTwoFragment newInstance(String jsonArray, String firstLevelName) {
        LinkListTwoFragment mFragment = new LinkListTwoFragment();

        Bundle bundle = new Bundle();
        bundle.putString(EXTRA_DATA, jsonArray);
        bundle.putString(EXTRA_FIRST_LEVEL_NAME, firstLevelName);

        mFragment.setArguments(bundle);
        return mFragment;
    }

    private void initView(View v) {
        rvLeft = v.findViewById(R.id.rv_left);
        rvRight = v.findViewById(R.id.rv_right);
        etKeyword = v.findViewById(R.id.et_keyword);
        ImageView ivDeleteKeyword = v.findViewById(R.id.iv_delete_keyword);

        ivDeleteKeyword.setOnClickListener(this);
        etKeyword.addTextChangedListener(this);

        llTitle = v.findViewById(R.id.ll_title);
        mScrollview = v.findViewById(R.id.horizontal_scroll);
    }


    private void initData() {
        assert getArguments() != null;
        String jsonArray = getArguments().getString(EXTRA_DATA);
        firstLevelName = getArguments().getString(EXTRA_FIRST_LEVEL_NAME);
        if (TextUtils.isEmpty(jsonArray)) {
            return;
        }
        llManagerLeft = new LinkListManager(mActivity, jsonArray, callback);
        llManagerLeft.init(rvLeft, tagLeft, this);
        llManagerRight = new LinkListManager(mActivity, "", callback);
        llManagerRight.init(rvRight, tagRight, this);
        title.add("全部");
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_delete_keyword:
                etKeyword.setText("");
                break;
            default:
                break;
        }
    }

    @Override
    public void onAttach(Context context) {
        mActivity = (Activity) context;
        if (context instanceof LinkCallback) {
            callback = (LinkCallback<T>) context;
        } else {
            throw new RuntimeException(context.toString() + " must implements LinkCallback");
        }
        super.onAttach(context);
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        mHandler.removeCallbacks(mRunnable);
        mHandler.postDelayed(mRunnable, 500);
    }

    private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (mActivity != null && etKeyword != null) {
                String keyword = etKeyword.getText().toString();
                if (TextUtils.isEmpty(keyword)) {
                    llManagerLeft.showCurData();
                    return;
                }
                //关键字搜索
//                llManagerLeft.searchByKeyword(etKeyword.getText().toString());
            }
        }
    };

    private boolean neverRight = true;//还没点击过第二列

    @Override
    public void moveToNextLevel(String mTag, List<T> oldData, int position, List<T> data) {

        if (mTag.equals(tagLeft)) {
            llManagerRight.refresh(data);

            if (neverRight) {
                if (historyData.size() == 1) {
                    addHistory(oldData, data);

                } else {
                    List<T>[] mList = historyData.get(1);
                    mList[1] = data;
                    historyData.add(mList);
                }
            }
            if (title.size() == 1) {
                title.add(callback.getName(oldData.get(position)));
            } else if (title.size() > 1) {
                title.remove(title.size() - 1);
                title.add(callback.getName(oldData.get(position)));
            }
        } else if (mTag.equals(tagRight)) {
            neverRight = false;
            llManagerLeft.refresh(oldData);
            llManagerRight.refresh(data);

            addHistory(oldData, data);
            title.add(callback.getName(oldData.get(position)));
        }

        refreshTitle();
    }

    private void refreshTitle() {
        llTitle.removeAllViews();
        for (final String value : title) {
            TextView textView = new TextView(mActivity);
            textView.setText(value);
            textView.setTextColor(mActivity.getResources().getColor(R.color.colorBlue));
            textView.setPadding(5, 5, 5, 5);
            llTitle.addView(textView);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showHistoryDataByIndex(title.indexOf(value));
                    showHistoryTitleByIndex(title.indexOf(value));
                }
            });
            if (title.indexOf(value) != title.size() - 1) {
                TextView tv = new TextView(mActivity);
                tv.setText(">");
                llTitle.addView(tv);
            }
        }
        mScrollview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mScrollview.post(new Runnable() {
                    public void run() {
                        mScrollview.fullScroll(View.FOCUS_RIGHT);
                    }
                });
            }
        });
    }


    private void addHistory(List<T> oldData, List<T> data) {
        List<T>[] mList = new ArrayList[2];
        mList[0] = oldData;
        mList[1] = data;
        historyData.add(mList);
    }

    @Override
    public void getAllData(String mTag, List<T> data) {

        if (mTag.equals(tagLeft)) {
            List<T>[] firstData = new ArrayList[2];
            firstData[0] = data;
            firstData[1] = new ArrayList<>();
            historyData.add(firstData);
        }
    }



    private void showHistoryDataByIndex(int index) {
        if (historyData.size() > 1 && historyData.size() > index) {
            List<T>[] mData = historyData.get(index);
            llManagerLeft.refresh(mData[0]);
            llManagerRight.refresh(mData[1]);
            historyData = historyData.subList(0, index + 1);
//            while (index < historyData.size()) {
//                historyData.remove(index);
//
//                index++;
//            }
            if (historyData.size() == 1) {
                neverRight = true;
            }
        }
    }

    private void showHistoryTitleByIndex(int index) {
        title = title.subList(0, index + 1);
        refreshTitle();
    }
}
